package com.example.shutdown_v1.schedule;

import com.example.shutdown_v1.service.DailyInspectionService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 每日巡检定时任务
 * 每天在指定时间自动执行巡检
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class DailyInspectionScheduler {

    private final DailyInspectionService inspectionService;

    /**
     * 每日定时巡检
     * 默认每天晚上22:00（10点）执行
     * Cron表达式：秒 分 时 日 月 周
     * 0 0 22 * * ? = 每天22:00:00执行
     */
    @Scheduled(cron = "${schedule.daily-inspection.cron:0 0 22 * * ?}")
    public void performDailyInspection() {
        log.info("========== 开始执行每日定时巡检 ==========");
        
        try {
            var records = inspectionService.performAllInspections();
            
            long compliantCount = records.stream()
                    .filter(r -> r.getIsCompliant() != null && r.getIsCompliant())
                    .count();
            long totalCount = records.size();
            
            log.info("========== 每日巡检完成 ==========");
            log.info("巡检店铺数: {}", totalCount);
            log.info("合规店铺数: {}", compliantCount);
            log.info("不合规店铺数: {}", totalCount - compliantCount);
            double complianceRate = totalCount > 0 ? (compliantCount * 100.0 / totalCount) : 0.0;
            log.info("合规率: {}%", String.format("%.1f", complianceRate));
            
        } catch (Exception e) {
            log.error("每日巡检执行失败", e);
        }
    }
    
    /**
     * 测试用：每5分钟执行一次（可在配置中启用）
     * 正式环境建议禁用
     */
    // @Scheduled(cron = "0 */5 * * * ?")
    public void performTestInspection() {
        log.debug("[测试] 执行测试巡检");
        performDailyInspection();
    }
}

